﻿layui.use(['form', "ajax", 'common', 'upload', 'msgbox', 'layedit'], function () {
    var form = layui.form;
    var $ = layui.$;
    var ajax = layui.ajax;
    var upload = layui.upload;
    var common = layui.common;
    var msgBox = layui.msgbox;
    var layEdit = layui.layedit;
    var summaryEdit = null;

    loadChannelList().success(init);

    function init() {
        var productId = $("#productId").val();

        layEdit.set({
            uploadImage: {
                url: '/api/Image/upload4layedit' //接口url
            }
        });

        initUploadTool(upload, msgBox, $, ajax);
        initSpe();
        toggleMinPrice();
        if (productId) {
            loadData(productId);
        }

        form.on('submit(*)', function (data) {
            var channelArray = [];
            $("input:checkbox[name='channel']:checked").each(function () { // 遍历name=test的多选框
                channelArray.push($(this).val()); // 每一个被选中项的值
            });
            var imageIds = [];
            $(".layui-upload-wrap").each(function () {
                imageIds.push($(this).data("id"));
            });
            var speArray = [];

            $(".spe-item").each(function () {
                var $this = $(this);
                var speItem = {
                    costPrice: $this.find('[name="costPrice"]').val(),
                    speName: $this.find('[name="speName"]').val()
                };
                speArray.push(speItem);
            });

            var formData = {
                productName: data.field.productName,
                fullDetail: getSummaryEdit(),
                summary: data.field.summary,
                channel: channelArray,
                imageIds: imageIds,
                speList: speArray,
                costPrice: parseFloat($("#min-price").find('[name=costPrice]').val())
            };

            msgBox.showLoading();
            var url = "/ProductManager/api/Product/SaveProduct";
            var method = "post";
            if (productId) {
                formData.productId = productId;
                url = "/ProductManager/api/Product/UpdateProduct?productId=" + productId;
                method = "put";
            }
            ajax[method](formData, url).success(function (response) {
                msgBox.closeLoading();
                if (response.isSuccessed) {
                    var pi = parent.layer.getFrameIndex(window.name);
                    parent.layer.close(pi);
                    parent.location.reload();
                } else {
                    common.msgError(response.errorMessage.Message);
                }
            });
            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        });

        summaryEdit = layEdit.build('fullDetail');
    }

    /**
     *
     * 加载详情
     * @param {any} productId
     */
    function loadData(productId) {
        if (productId) {
            $.getJSON("/ProductManager/api/Product/get/" + productId).done(function (response) {
                // 加载图片
                if (response.result.imageIdList.length > 0) {
                    $.each(response.result.imageIdList, function (index, imageItem) {
                        appendImageItem(imageItem);
                    });
                }
                // 分类
                if (response.result.channelList.length > 0) {
                    $.each(response.result.channelList, function (index, channelItem) {
                        $("[name=channel][value='" + channelItem.channelId + "']").prop("checked", true);
                    });
                    form.render('checkbox');
                }
                if (response.result.speList.length > 0) {
                    $.each(response.result.speList, function (index, speItem) {
                        appendSpeItem(speItem);
                    });
                    toggleMinPrice();
                    switchSpeVisible();
                    changeMinPrice();
                }
                $('[name=costPrice]').val(response.result.minPrice);
                $("#fullDetail").val(response.result.fullDetail);
                summaryEdit = layEdit.build('fullDetail');
                $("#summary").val(response.result.summary);
                $("#productName").val(response.result.productName);

                form.render();
            });
        }
    }

    function getSummaryEdit() {
        return layEdit.getContent(summaryEdit);
    }

    /**
     * 加载货架列表
     */
    function loadChannelList() {
        var $btnChannelList = $("#btn-channel-list");
        $btnChannelList.empty();
        return $.getJSON("/ProductManager/api/Product/Channel/GetList").done(function (response) {
            $.each(response, function (index, item) {
                $btnChannelList.append(
                    '<input type="checkbox" name="channel" title="' + item.channelName + '" lay-skin="primary" value="' + item.channelId + '"/>');
            });
            form.render('checkbox');
        });
    }

    /**
 * 初始化规格
 */
    function initSpe() {
        toggleMinPrice();
        switchSpeVisible();
        $("#btn-add-spe").click(function () {
            appendSpeItem();
            toggleMinPrice();
            switchSpeVisible();
        });
        $("#btn-add-spe-list").click(function () {
            appendSpeItem();
            toggleMinPrice();
            switchSpeVisible();
        });
    }

    function switchSpeVisible() {
        if ($(".spe-item").length === 0) {
            $("#spe-wra").hide();
            $("#btn-add-spe-list").show();
        } else {
            $("#spe-wra").show();
            $("#btn-add-spe-list").hide();
        }
    }

    /**
     * 添加规格项
     */
    function appendSpeItem(speItem) {
        var $items = $('<tr class="spe-item">\
                                    <td><input type="text" name="speName" maxlength="50" class="layui-input" lay-verify="required" /></td>\
                                    <td><input type="text" name="costPrice" placeholder="￥" class="layui-input" lay-verify="number"></td>\
                                    <td>\
                                        <div class="layui-btn-group">\
                                            <button class="layui-btn layui-btn-primary layui-btn-sm btn-delete" type="button">\
                                                <i class="layui-icon">&#xe640;</i>\
                                            </button>\
                                        </div>\
                                    </td>\
                            </tr>');
        if (speItem) {
            $items.find('[name=speName]').val(speItem.specificationName);
            $items.find('[name=costPrice]').val(speItem.costPrice);
        }
        $items.on("change", "[name=costPrice]", function () {
            changeMinPrice();
        });
   
        $items.on("click", ".btn-delete", function (evt) {
                $(evt.currentTarget).parents("tr").remove();
                if ($(".spe-item").length === 0) {
                    $("#spe-wra").hide();
                    $("#btn-add-spe-list").show();
                }
                toggleMinPrice();
        });
        $("#spe-item").append($items);
    }

    /**
     * 变换产品最低价
     */
    function toggleMinPrice() {
        var $minPrice = $("#min-price");
        if ($(".spe-item").length === 0) {
            $minPrice.show();
            $minPrice.find('[name=costPrice]').prop("disabled", false);
        } else {
            $minPrice.hide();
            $minPrice.find('[name=costPrice]').prop("disabled", true);
        }
    }

    /**
     * 变换最低价
     */
    function changeMinPrice() {
        var minPrice = 0;
        var prices = $(".spe-item").map(function () {
            if ($(this).find('[name=costPrice]').val() !== "") {
                return parseFloat($(this).find('[name=costPrice]').val());
            }
            return 0;
        });

        if (prices.length > 0) {
            minPrice = Math.min.apply(null, prices);
        }

        $("#min-price").find('[name=costPrice]').val(minPrice);
    }

    /**
     * 初始化上传组件
     */
    function initUploadTool() {
        var $uploadList = $("#upload-list");
        var $imageUploader = $("#uploader-btn");

        upload.render({
            elem: '#uploader-btn',
            url: '/api/image/upload',
            accept: "images",
            before: function () {
                msgBox.showLoading();
            },
            size: 1024 * 2,
            done: function (res) {
                msgBox.closeLoading();

                appendImageItem(res);
            }
        });

        $uploadList.on("click", ".btn-delete", function (evt) {
            layer.confirm('真的删除行么', function (index) {
                var id = $(evt.currentTarget).data("id");
                msgBox.showLoading();
                ajax.delete({}, "/api/file/delete/" + id).success(function (response) {
                    msgBox.closeLoading();
                    $(evt.currentTarget).parents(".layui-upload-wrap").remove();
                    $imageUploader.prop("disabled", false);
                });
                layer.close(index);
            });
        });
    }

    function appendImageItem(res) {
        var $imageUploader = $("#uploader-btn");
        var $uploadList = $("#upload-list");
        $uploadList.append('<div class="layui-upload-wrap" data-id="' + res.imageId + '">'
            + '  <img class= "layui-upload-img" width = "150" src = "/api/image/download/' + res.imageId + '" />'
            + '  <p>'
            + '     <button type="button" class="layui-btn layui-btn-primary layui-btn-fluid btn-delete" data-lay data-id="' + res.imageId + '">删除</button>'
            + '  </p>'
            + '</div >');
        if ($(".layui-upload-wrap").length === 4) {
            $imageUploader.prop("disabled", true);
        }
    }
});